#!/usr/bin/env python
# -*- coding: utf-8 -*-

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
import time
import os, shutil


class WebTestBase():

    def __init__(self, control=False, usercache=False, updatecahe=False):
        # super(WebTestBase, self).__init__(**kwargs)
        if control:
            print("start control chrome")
            self.__control_chrome()
        elif usercache:
            self.__update_init_chrome(updatecahe)
        else:
            self.__init_chrome()

        print("<<<<<<  opened the browser. start to login web ... >>>>>>>")

    def __init_chrome(self,option=None):
        if option :
            option.add_experimental_option('excludeSwitches', ['enable-automation'])  # 开启实验性功能
            # 去除特征值
            option.add_argument("--disable-blink-features=AutomationControlled")
        else:
            option = webdriver.ChromeOptions()
            option.add_experimental_option('excludeSwitches', ['enable-automation'])  # 开启实验性功能
            # 去除特征值
            option.add_argument("--disable-blink-features=AutomationControlled")
            # 实例化谷歌
        self.driver = webdriver.Chrome(options=option)
        # 修改get方法
        script = '''object.defineProperty(navigator,'webdriver',{undefinedget: () => undefined})'''
        # execute_cdp_cmd用来执行chrome开发这个工具命令,反爬
        self.driver.execute_cdp_cmd("Page.addScriptToEvaluateOnNewDocument", {"source": script})
        self.driver.maximize_window()
        self.driver.implicitly_wait(30)

    def __update_init_chrome(self, updatecahe=False):
        option = webdriver.ChromeOptions()
        # 添加保持登录的数据路径：安装目录一般在
        # C:\Users\****\AppData\Local\Google\Chrome\User Data
        # 打开浏览器时运行会报错，所以复制一个目录来调用
        userdatadir = r"C:\Users\65182\AppData\Local\Google\Chrome\User Data"
        target_dir = r"C:\Users\65182\AppData\Local\Google\Chrome\User Data_Backup"
        if updatecahe:
            if os.path.exists(target_dir):
                shutil.rmtree(target_dir)
            shutil.copytree(userdatadir, target_dir)
            option.add_argument("user-data-dir={}".format(target_dir))
        self.__init_chrome()

    def __control_chrome(self):
        # 本地启动chrome  ,可以考虑加参数--user-data-dir
        cmd = r"C:\Users\65182\AppData\Local\Google\Chrome\Application\chrome.exe --remote-debugging-port=9227"
        os.system(cmd)
        time.sleep(3)
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9227")  # 前面设置的端口号
        chrome_options.add_argument('--ignore-certificate-errors')
        chrome_options.add_argument('--ignore-ssl-errors')
        chrome_options.add_experimental_option('excludeSwtiches', ['enable-automation', 'enable-logging'])
        self.driver = webdriver.Chrome(options=chrome_options)
        self.driver.maximize_window()
        self.driver.implicitly_wait(30)

    def open_url(self, url):
        self.driver.get(url)

    def send_keys(self, element, by, conment):
        """

        :param element:
        :param by:  id,xpath,name
        :param conment:
        :return:
        """
        map = {"id": By.ID, "xpath": By.XPATH, "name": By.NAME}
        self.wait_element(by=map[by], element=element)
        self.driver.find_element(by=map[by], value=element).clear()
        self.driver.find_element(by=map[by], value=element).send_keys(conment)

    def click(self, element, by):
        """
        :param element:
        :param by:  id,xpath,name
        :return:
        """
        map = {"id": By.ID, "xpath": By.XPATH, "name": By.NAME}
        self.wait_element(by=map[by], element=element)
        self.driver.find_element(by=map[by], value=element).click()

    def wait_element(self, element, by):
        """
        :param element:
        :param by:     id,xpath,name
        :return:
        """
        map = {"id": By.ID, "xpath": By.XPATH, "name": By.NAME}
        for t in range(5):
            if self.driver.find_element(by=map[by], value=element):
                break
            else:
                if t == 4:
                    print("cant find element.")
                    return False
            time.sleep(5)
        return True

    def login_infinity(self):

        self.send_keys(element="pname", by="name", conment="admin")
        self.send_keys(element="pword", by="name", conment="123456")
        self.click(element="btn_login", by="id")
        time.sleep(5)

    def click_into_cluster_management(self):
        ActionChains(self.driver).move_to_element(
            self.driver.find_element_by_xpath("//*[@id=\"navbar\"]/ul/ul/li[2]/a/b")).perform()
        time.sleep(1)

        ActionChains(self.driver).double_click(
            self.driver.find_element_by_xpath("//*[@id=\"navbar\"]/ul/ul/li[2]/ul/li[3]/a")).perform()

    def click_into_setup_guide(self):
        ActionChains(self.driver).move_to_element(
            self.driver.find_element_by_xpath("//*[@id=\"navbar\"]/ul/ul/li[2]/a/b")).perform()
        time.sleep(1)

        ActionChains(self.driver).double_click(
            self.driver.find_element_by_xpath("//*[@id=\"navbar\"]/ul/ul/li[2]/ul/li[5]/a")).perform()

    def move_to_element(self, element, by):
        """

        :param element:
        :param by:   id,xpath,name
        :return:
        """
        map = {"id": By.ID, "xpath": By.XPATH, "name": By.NAME}

        ActionChains(self.driver).move_to_element(
            self.driver.find_element(by=map[by], value=element)).perform()

    def ActionChains_double_click(self, element, by):
        """

                :param element:
                :param by:   id,xpath,name
                :return:
                """

        map = {"id": By.ID, "xpath": By.XPATH, "name": By.NAME}
        ActionChains(self.driver).move_to_element(
            self.driver.find_element(by=map[by], value=element)).perform()
        time.sleep(1)
        ActionChains(self.driver).double_click(
            self.driver.find_element(by=map[by], value=element)).perform()

    def run_js(self, js):

        self.driver.execute_script(js)

    # def __del__(self):
    #     self.driver.close()
